package com.notelapierdas.activities;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.notelapierdas.R;
import com.notelapierdas.objects.Deal;
import com.notelapierdas.objects.DealTimer;
import com.notelapierdas.twitter.AlmacenCredenciales;
import com.notelapierdas.twitter.TokenAccesoOAuth;

public class DealActivity extends ActionBarActivity implements OnClickListener {

	RelativeLayout conditions_layout, highlights_layout, business_layout;
	Deal myDeal;
	Button conditionsButton, highlightsButton, infOfertaButton,
			compartirOfertaButton, viewMap;
	TextView timerTextView;
	DealTimer timer;
	private SharedPreferences sharedPreferences;
	private static final int WEBVIEWACTIVITY = 1;
	private static final int FACEBOOK =0;

	// ContextMenu
	Resources res;
	private final int CONTEXT_MENU_ID = 1;
	private IconContextMenu iconContextMenu = null;
	private final int MENU_ITEM_1_ACTION = 1;
	private final int MENU_ITEM_2_ACTION = 2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.deal_layout);
		super.onCreate(savedInstanceState);

		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

		Bundle b = getIntent().getExtras();
		myDeal = b.getParcelable("com.notelapierdas.objects.Deal");

		initialize();
		initializeContextMenu();
		conditionsButton.performClick();

	}

	private void initializeContextMenu() {
		res = getResources();
		iconContextMenu = new IconContextMenu(this, CONTEXT_MENU_ID);
		iconContextMenu.addItem(res, "Facebook", R.drawable.facebook_icon32,
				MENU_ITEM_1_ACTION);
		iconContextMenu.addItem(res, "Twitter", R.drawable.twitter_icon32,
				MENU_ITEM_2_ACTION);

		registerForContextMenu(compartirOfertaButton);

		iconContextMenu
				.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
					@Override
					public void onClick(int menuId) {
						switch (menuId) {
						case MENU_ITEM_1_ACTION:
							shareOnFacebook();
							break;
						case MENU_ITEM_2_ACTION:
							shareOnTwitter();
							break;
						}
					}
				});
	}

	private void initialize() {
		// MainDealObject

		TextView title = (TextView) findViewById(R.id.MainDealObject_TextView_title);
		TextView original_price = (TextView) findViewById(R.id.MainDealObject_TextView_originalprice);
		TextView discount = (TextView) findViewById(R.id.MainDealObject_TextView_discount);
		TextView deal_price = (TextView) findViewById(R.id.MainDealObject_TextView_dealprice);
		timerTextView = (TextView) findViewById(R.id.DealActivity_TextView_timer);
		ImageView image = (ImageView) findViewById(R.id.MainDealObject_ImageView_picture);

		title.setText(myDeal.getTitle().getShortTitle());
		original_price.setText("$" + myDeal.getPrice().getOriginalPrice());
		discount.setText(myDeal.getPrice().getDiscount() + "%");
		deal_price.setText("$" + myDeal.getPrice().getDealPrice());
		// image.setImageBitmap(myDeal.getPicture());
		logoImageView.setVisibility(View.GONE);

		// DealInformationObject
		TextView conditionsInfo = (TextView) findViewById(R.id.DealInformationObject_TextView_conditions);
		TextView highlightsInfo = (TextView) findViewById(R.id.DealInformationObject_TextView_highlights);
		TextView businessTitle = (TextView) findViewById(R.id.DealInformationObject_TextView_businessTitle);
		TextView businessInfo =   (TextView) findViewById(R.id.DealInformationObject_TextView_businessInfo);
		
		
		conditions_layout = (RelativeLayout) findViewById(R.id.DealInformationConditions_layout);
		highlights_layout = (RelativeLayout) findViewById(R.id.DealInformationHighlights_layout);
		business_layout = (RelativeLayout) findViewById(R.id.DealInformationBusiness_layout);

		conditionsInfo.setText(myDeal.getConditions());
		highlightsInfo.setText(myDeal.getHighlights());
		businessTitle.setText(myDeal.getBusiness().getName());
		businessInfo.setText(myDeal.getBusiness().getAddress().getName()+"\n"+myDeal.getBusiness().getTelephone()+"\n"+myDeal.getBusiness().getEmail());
		
		
		// Buttons
		conditionsButton = (Button) findViewById(R.id.DealInformationObject_Button_conditions);
		conditionsButton.setOnClickListener(this);
		highlightsButton = (Button) findViewById(R.id.DealInformationObject_Button_highlights);
		highlightsButton.setOnClickListener(this);
		infOfertaButton = (Button) findViewById(R.id.DealInformationObject_Button_business);
		infOfertaButton.setOnClickListener(this);
		compartirOfertaButton = (Button) findViewById(R.id.DealActivity_Button_compartirOferta);
		compartirOfertaButton.setOnClickListener(this);
		
		viewMap =   (Button) findViewById(R.id.DealInformationObject_Button_ViewMap);
		viewMap.setOnClickListener(this);
		// Timer
		timer = new DealTimer(timerTextView);
		timer.start();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.DealInformationObject_Button_conditions: {
			highlights_layout.setVisibility(View.GONE);
			business_layout.setVisibility(View.GONE);
			conditions_layout.setVisibility(View.VISIBLE);

			conditionsButton.setEnabled(false);
			highlightsButton.setEnabled(true);
			infOfertaButton.setEnabled(true);

			break;
		}
		case R.id.DealInformationObject_Button_highlights: {
			business_layout.setVisibility(View.GONE);
			conditions_layout.setVisibility(View.GONE);
			highlights_layout.setVisibility(View.VISIBLE);

			conditionsButton.setEnabled(true);
			highlightsButton.setEnabled(false);
			infOfertaButton.setEnabled(true);

			break;
		}
		case R.id.DealInformationObject_Button_business: {
			highlights_layout.setVisibility(View.GONE);
			conditions_layout.setVisibility(View.GONE);
			business_layout.setVisibility(View.VISIBLE);

			conditionsButton.setEnabled(true);
			highlightsButton.setEnabled(true);
			infOfertaButton.setEnabled(false);
			

			break;
		}case R.id.DealInformationObject_Button_ViewMap: {
			 Intent i = new Intent(getApplicationContext(),
					 GoogleMapsActivity.class);
			 i.putExtra("latitude", myDeal.getBusiness().getAddress().getLatitude());
			 i.putExtra("longitude", myDeal.getBusiness().getAddress().getLongitude());
					 startActivity(i);
			break;
		}
		case R.id.DealActivity_Button_compartirOferta: {
			showDialog(CONTEXT_MENU_ID);
			break;
		}

		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == CONTEXT_MENU_ID) {
			return iconContextMenu.createMenu("Share");
		}
		return super.onCreateDialog(id);
	}

	private void shareOnFacebook() {
		Intent postOnFacebookWallIntent = new Intent(this,
				ShareOnFacebookActivity.class);
		postOnFacebookWallIntent.putExtra("deal", myDeal);
		startActivity(postOnFacebookWallIntent);
	}

	private void shareOnTwitter() {
		startActivityForResult(new Intent().setClass(getApplicationContext(),
				TokenAccesoOAuth.class), WEBVIEWACTIVITY);

	}

	private Twitter loginTwitter() {
		String[] tokens = new AlmacenCredenciales(sharedPreferences).lee();
		AccessToken a = new AccessToken(tokens[0], tokens[1]);

		Twitter twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(
				com.notelapierdas.twitter.Constants.CONSUMER_KEY,
				com.notelapierdas.twitter.Constants.CONSUMER_SECRET);

		twitter.setOAuthAccessToken(a);

		return twitter;
	}

	private void sendTweet(SharedPreferences sharedPrefs, String message)
			throws Exception {
		Twitter twitter = loginTwitter();
		twitter.updateStatus(message);

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		timer.cancel();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case (WEBVIEWACTIVITY): {
			try {
				sendTweet(sharedPreferences, myDeal.getTitle().getLongTitle());
			} catch (Exception e) {
				e.printStackTrace();
			}
			Toast.makeText(this, "Share On twitter...", Toast.LENGTH_LONG)
					.show();
			break;
				}
	}

}
}
